#include "./util.h"
#include <QApplication>
#include <QDebug>
#include <QGraphicsDropShadowEffect>
#include <QPixmap>
#include <QPropertyAnimation>
#include <QScreen>


static const QColor GRAY_COLOR = QColor::fromRgb(204, 204, 204);
static const char *BORDER_STYLE =
    ".QWidget { background-color: white; border-radius: 10px; }";

void set_lb_img(QLabel *label, const QString &path) {
    QPixmap pixmap = QPixmap::fromImage(QImage(path));
    int w = label->width();
    int h = label->height();
    label->setPixmap(pixmap.scaled(w, h));
}

void set_window_custom(QWidget *win) {
    win->setWindowFlags(Qt::FramelessWindowHint);
    win->setAttribute(Qt::WA_TranslucentBackground);
}

void set_window_card(QWidget *win, qreal blur) {
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
    shadow->setBlurRadius(blur);
    shadow->setOffset(0);
    shadow->setColor(GRAY_COLOR);

    win->setGraphicsEffect(shadow);
    win->setStyleSheet(BORDER_STYLE);
}

QPropertyAnimation *run_scale_anim_close(QWidget *win, int msec) {
    QPropertyAnimation *anim = new QPropertyAnimation(win, "geometry");
    QRect target = win->geometry();
    int cx = (target.left() + target.right()) / 2;
    int cy = (target.top() + target.bottom()) / 2;
    int min_w = target.width() / 4;
    int min_h = target.height() / 4;
    QRect min(cx - min_w / 2, cy - min_h / 2, min_w, min_h);
    anim->setDuration(msec);
    anim->setEasingCurve(QEasingCurve::Linear);
    anim->setStartValue(target);
    anim->setEndValue(min);
    anim->start(QAbstractAnimation::DeleteWhenStopped);
    return anim;
}

QPropertyAnimation *run_scale_anim(QWidget *win, int msec, bool to_max) {
    QRect parent_rect = QApplication::primaryScreen()->geometry();
    QWidget *parent = win->parentWidget();
    if (parent != nullptr) {
        parent_rect = parent->geometry();
    }

    QSize max = win->size();
    QSize min = QSize(max.width() / 4, max.height() / 4);

    int cx = parent_rect.left() + parent_rect.width() / 2;
    int cy = parent_rect.top() + parent_rect.height() / 2;

    QPropertyAnimation *anim = new QPropertyAnimation(win, "geometry");
    anim->setDuration(msec);
    anim->setEasingCurve(QEasingCurve::InOutQuad);

    QRect min_rect(cx - min.width() / 2, cy - min.height() / 2, min.width(),
                   min.height());
    QRect max_rect(cx - max.width() / 2, cy - max.height() / 2, max.width(),
                   max.height());
    if (to_max) {
        anim->setStartValue(min_rect);
        anim->setEndValue(max_rect);
    } else {
        anim->setStartValue(max_rect);
        anim->setEndValue(min_rect);
    }
    anim->start(QAbstractAnimation::DeleteWhenStopped);
    return anim;
}
